<template>
  <div>
<!--    面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

<!--    卡片视图区域-->
    <el-card class="box-card">
<!--      添加角色列表区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

<!--      角色列表区域 -->
      <el-table border :data="rolesList" stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop': '', 'vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
<!--              渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--              渲染二级权限 三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '': 'bdtop', 'vcenter']">
                  <!--            通过for循环嵌套渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--            三级权限 -->
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
<!--            slot-scope="scope"-->
            <!--              修改按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showRolesDialog(scope.row.id)">修改</el-button>
            <!--              删除按钮 -->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolesById(scope.row.id)">删除</el-button>
            <!--              分配角色按钮-->
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!--    添加权限对话框-->
    <el-dialog
      title="添加权限"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogClosed"
      >
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input clearable v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input clearable v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
<!--      底部区域-->
      <span solt="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRole">确定</el-button>
      </span>
    </el-dialog>
<!--    修改权限对话框-->
    <el-dialog
      title="修改权限"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input clearable v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input clearable v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span solt="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editRole">确定</el-button>
      </span>
    </el-dialog>
<!--    分配权限对话框-->
    <el-dialog
      title="提示"
      :visible.sync="setRoleDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
      >
      <el-tree
        :data="rightList"
        :props="treeProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
        >
      </el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 控制分配权限对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 所有权限的数据
      rightList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 所有角色列表数据
      rolesList: [],
      // 添加权限列表数据
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 默认选中的节点id值数据
      defKeys: [],
      // 修改权限对话框列表数据
      editForm: {},
      // 控制修改权限对话框的显示与隐藏
      editRoleDialogVisible: false,
      // 控制对话框的显示与隐藏
      addRoleDialogVisible: false,
      // 修改权限信息的验证规则对象
      editFormRules: {
        roleName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入权限描述', trigger: 'blur' }
        ]
      },
      // 添加权限信息的验证规则对象
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入权限描述', trigger: 'blur' }
        ]
      },
      // 当前即将分配权限的ID
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 点击修改按钮，显示对话框
    async showRolesDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限信息失败！')
      }
      this.editForm = res.data
      this.editRoleDialogVisible = true
    },
    // 取消按钮重置对话框信息
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 点击确定按钮修改权限信息
    editRole() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        // 发起权限信息的数据请求
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, this.editForm)
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户权限信息数百')
        }
        this.editRoleDialogVisible = false
        this.$message.success('更新角色权限信息成功')
        this.getRolesList()
      })
    },
    // 点击删除按钮弹框警告，确认删除是否
    async removeRolesById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色权限信息，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果权限确认伤处，则返回值为字符串 confirm， 如果取消，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色权限失败！')
      }
      this.$message.success('删除角色权限成功！')
      this.getRolesList()
    },
    // 获取权限列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 根据ID删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该权限，是否继续？', '删除权限', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      // this.getRolesList()
      role.children = res.data
      this.$message.success('已经删除！')
    },
    // 监听添加权限对话框关闭事件
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 点击按钮确认添加权限
    addRole() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加权限的网络请求
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        // console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取所有权限的数据失败')
      }
      // console.log(res)
      // 把获取到的权限数据保存到 data 中
      this.rightList = res.data
      // console.log(this.rightList)
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)
      this.setRoleDialogVisible = true
    },
    // 通过递归的形式获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        // 如果当前node 节点不包含children 属性，则是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
      this.roleId = ''
    },
    // 点击确定为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(' ')
      // console.log(idStr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色权限失败！')
      }
      this.$message.success('分配角色权限成功！')
      this.getRolesList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style scoped lang="less">
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
  }
.vcenter {
  display: flex;
  align-items: center;
}
.el-table{
  margin-top: 20px;
}
</style>
